﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using System.Collections;

public class ConvertImage
{
	[MenuItem("Coser/Tools/Convert Image")]
	public static void SplitPNG32()
	{
		var texs = Selection.objects;
		foreach (var o in texs)
		{
			var tex = o as Texture2D;
			SplitTextureToAlpha8AndRGB24(tex, "");
		}
	}

	/// <summary>
	/// 
	/// </summary>
	/// <param name="tex"></param>
	/// <param name="alphaPath"></param>
	/// <returns>0 rgbFilePath, 1 alphaFilePath</returns>
	public static List<string> SplitTextureToAlpha8AndRGB24(Texture2D tex, string alphaPath)
	{
		if (ModefyTextureSettings(ref tex))
		{
			var rgbTex = new Texture2D(tex.width, tex.height, TextureFormat.RGB24, false);
			var alphaTex = new Texture2D(tex.width, tex.height, TextureFormat.Alpha8, false);
			if (tex.format == TextureFormat.RGBA32 || tex.format == TextureFormat.ARGB32)
			{
				var rgbColor = new Color();
				var alphaColor = new Color();
				for (int i = 0; i < tex.width; i++)
				{
					for (int j = 0; j < tex.height; j++)
					{ 
						var color = tex.GetPixel(i, j);
						rgbColor.r = color.r;
						rgbColor.g = color.g;
						rgbColor.b = color.b;
						alphaColor.a = color.a;
						rgbTex.SetPixel(i, j, rgbColor); 
						alphaTex.SetPixel(i, j, alphaColor);
					}
				}
			}

			rgbTex.Apply();
			alphaTex.Apply();

			var rgbBytes = rgbTex.EncodeToPNG();
			Debug.Log(rgbBytes.Length);
			var alphaBytes = alphaTex.EncodeToPNG();
			Debug.Log(alphaBytes.Length);

			var fullPath = AssetDatabase.GetAssetPath(tex);

			var fileName = Path.GetFileNameWithoutExtension(fullPath);
			var path = Directory.GetParent(fullPath);
			var alpha8FilePath = alphaPath + "/alpha_" + fileName + ".png";
			var rgbFilePath = path + "/" + fileName + ".jpg";
			Debug.Log(Directory.GetCurrentDirectory());
			if (!Directory.Exists(alphaPath))
			{
				Directory.CreateDirectory(alphaPath);
			}

			Debug.Log("Save alpha File To:" + alpha8FilePath);
			File.WriteAllBytes(rgbFilePath, rgbBytes);
			File.WriteAllBytes(alpha8FilePath, alphaBytes);

			var pathStr = "Assets/_old_" + fullPath;
			var backUpPath = Directory.GetParent(pathStr);
			backUpPath.Create();


			File.Move(fullPath, pathStr);
			//TODO:from file
			return new List<string>() { rgbFilePath, alpha8FilePath };
		}
		return null;
	}

	public static bool ModefyTextureSettings(ref Texture2D tex)
	{
		var path = AssetDatabase.GetAssetPath(tex);
		Debug.Log("Source Texture At:" + path);
		var importer = AssetImporter.GetAtPath(path) as TextureImporter;

		if (importer != null)
		{
			importer.textureType = TextureImporterType.Advanced;
			//importer.alphaIsTransparency = true;
			importer.grayscaleToAlpha = false;
			importer.linearTexture = false;
			importer.wrapMode = TextureWrapMode.Clamp;
			importer.npotScale = TextureImporterNPOTScale.None;
			importer.mipmapEnabled = false;
			importer.textureFormat = TextureImporterFormat.RGBA32;
			importer.compressionQuality = 100;
			importer.isReadable = true;

			//importer.spriteImportMode = SpriteImportMode.Single;
			//importer.spritePixelsToUnits = 100;
		}
		AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
		tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;

		return true;
	}

	public static Texture2D ImportTexture2D(string path, TextureImporterFormat format)
	{
		var importer = AssetImporter.GetAtPath(path) as TextureImporter;

		if (importer != null)
		{
			importer.textureType = TextureImporterType.Advanced;
			//importer.alphaIsTransparency = true;
			importer.grayscaleToAlpha = false;
			importer.linearTexture = false;
			importer.wrapMode = TextureWrapMode.Clamp;
			importer.npotScale = TextureImporterNPOTScale.None;
			importer.mipmapEnabled = false;
			importer.textureFormat = format;
			importer.compressionQuality = 100;
			importer.isReadable = false;

			//importer.spriteImportMode = SpriteImportMode.Single;
			//importer.spritePixelsToUnits = 100;
		}
		AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
		var tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
		return tex;

	}
}
